package com.eliansun.util;

import net.dongliu.requests.Requests;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 代理请求
 * ljh
 */
public class ProxyUtil {
    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

    public static String doRequest(String targetUrl, Map<String, String> headers) {

        // 代理服务器
        String proxyServer = "transfer.mogumiao.com";
        int proxyPort = 9001;

        // 代理隧道验证信息
        String proxyUser = "YIzGy0xocvova0jk";
        String proxyPass = "MoCmBoiDp0rmMKNo";

        try {

            //该部分必须在获取connection前调用
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            URL url = new URL(targetUrl);
            Authenticator.setDefault(new ProxyAuthenticator(proxyUser, proxyPass));

            // 创建代理服务器地址对象
            InetSocketAddress addr = new InetSocketAddress(proxyServer, proxyPort);
            // 创建HTTP类型代理对象
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

            // 设置通过代理访问目标页面
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
            headers.forEach((k, v) -> {
                connection.setRequestProperty(k, v);
            });
            // 解析返回数据
            byte[] response = readStream(connection.getInputStream());
            return new String(response, "gbk");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将输入流转换成字符串
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;

        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();

        return outSteam.toByteArray();
    }

    public static void main(String[] args) {
        String path = "https://mdskip.taobao.com/core/initItemDetail.htm?isUseInventoryCenter=false&cartEnable=true&service3C=false&isApparel=false&isSecKill=false&tmallBuySupport=true&isAreaSell=false&tryBeforeBuy=false&offlineShop=false&itemId=19032480524&showShopProm=false&isPurchaseMallPage=false&itemGmtModified=1543434201000&isRegionLevel=false&household=false&sellerPreview=false&queryMemberRight=true&addressLevel=2&isForbidBuyItem=false&callback=setMdskip&timestamp=1543480603930&isg=null&isg2=BBQUxYGMMziPmqf9fV26lUdd5VJGxTxg2dBXeq71oB8imbTj1n0I58oYndGkYXCv";

//        String header = "https://detail.tmall.com/item.htm?id=19032480524&rn=cce20ad9127f88d67778dd71b1142595";
        Map<String,String> header = new HashMap<>();
        header.put("Referer","https://detail.tmall.com/item.htm?id=19032480524&rn=cce20ad9127f88d67778dd71b1142595");
        System.out.println(Requests.get(path).headers(header).send().readToText());
    }
}
